package com.xishu.service;

import com.xishu.config.Config;
import com.xishu.util.OssService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * 对象存储服务
 * ！！！！！！！！！！！！不是指的JAVA里面的object对象！！！！！！！！！！！！！
 */
public class ObjectService {
    private static Logger logger = LoggerFactory.getLogger(ObjectService.class);
    private static ObjectService instance = new ObjectService();
    private Config config = Config.getInstance();

    private ObjectService() {

    }

    public static ObjectService getInstance() {
        return instance;
    }

    /**
     * 获取图片的ID
     * 拼接域名之后的路径
     *
     * @param objectId
     * @return
     */
    public String getImgUrl(String objectId) {
        StringBuilder sb = new StringBuilder();

        sb.append("https://");

        if (config.isAliyun()) {
            sb.append(config.getProductBucketEndpoint());
        } else {
            sb.append(config.getS3BucketEndPoint());
        }

        sb.append("/");
        sb.append(objectId);
        return sb.toString();
    }

    /**
     * 上传对象
     *
     * @param bucketName
     * @param objectName
     * @param srcFile
     */
    public void uploadObject(String bucketName, String objectName, File srcFile) {
        if (config.isAliyun()) {
            OssService.getInstance().uploadObject(bucketName, objectName, srcFile);
        } else {
            S3Service.getInstance().uploadObject(bucketName, objectName, srcFile);
        }
    }

    /**
     * 上传文件到桶
     *
     * @param srcFile
     */
    public void uploadObject(File srcFile) {
        if (config.isAliyun()) {
            OssService.getInstance().uploadObject(srcFile);
        } else {
            S3Service.getInstance().uploadObject(srcFile);
        }
    }


    /**
     * 下载文件
     *
     * @param objectName
     * @return
     */
    public File downloadFile(String objectName) throws Throwable {
        if (config.isAliyun()) {
            logger.info("will download file {}", objectName);
            String publicBucketName = config.getPublicBucketName();
            return OssService.getInstance().downloadFile(publicBucketName, objectName);
        } else {
            logger.info("will download file {}", objectName);
            String s3BucketName = config.getS3BucketName();
            File file = S3Service.getInstance().downloadFile(s3BucketName, objectName);
            logger.info("download file path is {}", file.getAbsolutePath());
            return file;
        }
    }
}
